package com.zxl.yjb.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tmall.ultraviewpager.UltraViewPager;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.home.SkillRegisterActivity;
import com.zxl.yjb.activity.home.WebViewActivity;
import com.zxl.yjb.activity.home.news.LocationNewsActivity;
import com.zxl.yjb.activity.home.order.OrderCreateActivity;
import com.zxl.yjb.activity.home.order.OrderSendActivity;
import com.zxl.yjb.activity.home.order.OrderTakeActivity;
import com.zxl.yjb.activity.home.order.ServiceSelectActivity;
import com.zxl.yjb.activity.home.position.PositionActivity;
import com.zxl.yjb.activity.home.sharemessage.ShareMessageClassifyActivity;
import com.zxl.yjb.adapter.BannerPagerAdapter;
import com.zxl.yjb.adapter.MenuItemAdapter;
import com.zxl.yjb.base.LazyBaseFragment;
import com.zxl.yjb.bean.BannerBean;
import com.zxl.yjb.bean.MenuClassifyBean;
import com.zxl.yjb.bean.ReadStatusBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.LogUtil;
import com.zxl.yjb.widget.PagerRecyclerView.HorizontalPageLayoutManager;
import com.zxl.yjb.widget.PagerRecyclerView.MyRecyclerView;
import com.zxl.yjb.widget.PagerRecyclerView.PagingScrollHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;

public class HomeFragment extends LazyBaseFragment implements IUnReadMessageObserver{


    @BindView(R.id.iv_shopping_message)
    ImageView iv_shopping_message;
    @BindView(R.id.iv_isRead)
    ImageView iv_isRead;
    @BindView(R.id.iv_isRead_send)
    ImageView iv_isRead_send;
    @BindView(R.id.vp_banner)
    UltraViewPager vp_banner;
    @BindView(R.id.ll_jinengzhuce)
    LinearLayout ll_jinengzhuce;
    @BindView(R.id.ll_fadanliebiao)
    LinearLayout ll_fadanliebiao;
    @BindView(R.id.ll_yijianfadan)
    LinearLayout ll_yijianfadan;
    @BindView(R.id.ll_jiedanweizhi)
    LinearLayout ll_jiedanweizhi;
    @BindView(R.id.ll_jiedanliebiao)
    LinearLayout ll_jiedanliebiao;
    @BindView(R.id.ll_index_circle)
    LinearLayout ll_index_circle;
    @BindView(R.id.rv_menu_list)
    MyRecyclerView rv_menu_list;
    @BindView(R.id.tv_msg_num)
    TextView tvMsgNum;

    private ArrayList<BannerBean> bannerList = new ArrayList<>();
    private BannerPagerAdapter bannerPagerAdapter;

    private ArrayList<MenuClassifyBean> menuClassifyList = new ArrayList<>();
    private HorizontalPageLayoutManager horizontalPageLayoutManager;
    private MenuItemAdapter menuItemAdapter;
    PagingScrollHelper scrollHelper = new PagingScrollHelper();
    private DataManager dataManager;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
    }

    @Override
    protected void main() {

        bannerPagerAdapter = new BannerPagerAdapter(getActivity(), bannerList);
        vp_banner.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
        vp_banner.setAutoScroll(2000);
//        vp_banner.getIndicator().setFocusResId(0).setNormalResId(0);
        vp_banner.initIndicator();
        vp_banner.getIndicator().setFocusResId(R.mipmap.banner_on).setNormalResId(R.mipmap.banner_off)
                .setRadius((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
        vp_banner.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        vp_banner.getIndicator().setMargin(0, 0, 0, 90);
        vp_banner.getIndicator().build();
        vp_banner.setAdapter(bannerPagerAdapter);
        vp_banner.setInfiniteLoop(true);
        bannerPagerAdapter.notifyDataSetChanged();
        bannerPagerAdapter.setOnItemClickListener(new BannerPagerAdapter.ItemClickListener() {
            @Override
            public void onitemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url",bannerList.get(position).getUrl());
                startActivity(intent);
            }
        });

        horizontalPageLayoutManager = new HorizontalPageLayoutManager(2,4);
        rv_menu_list.setLayoutManager(horizontalPageLayoutManager);
        menuItemAdapter = new MenuItemAdapter(R.layout.item_menu_classify,menuClassifyList);
        rv_menu_list.setAdapter(menuItemAdapter);
        scrollHelper.setUpRecycleView(rv_menu_list);
        scrollHelper.setOnPageChangeListener(new PagingScrollHelper.onPageChangeListener() {
            @Override
            public void onPageChange(int index) {
                if (ll_index_circle.getChildCount()>0)
                {
                    for (int i = 0; i < ll_index_circle.getChildCount(); i++) {
                        ((ImageView)ll_index_circle.getChildAt(i)).setImageResource(R.mipmap.index_off);
                    }
                    ((ImageView)ll_index_circle.getChildAt(index)).setImageResource(R.mipmap.index_on);
                }
            }
        });

        menuItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(),ServiceSelectActivity.class);
                intent.putExtra("id",menuClassifyList.get(position).getId());
                intent.putExtra("pid",menuClassifyList.get(position).getPid());
                intent.putExtra("name",menuClassifyList.get(position).getName());
                intent.putExtra("origin",HomeFragment.class.getName());
                startActivity(intent);
            }
        });


        getBannerList();
        getClassifyMenu();

        //注册融云im，未读消息的接受
        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };

        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, conversationTypes);

    }


    private void getBannerList()
    {
        dataManager = new DataManager();
        Map map = new HashMap();
        ObserverOnNextListener<List<BannerBean>> listener = new ObserverOnNextListener<List<BannerBean>>() {
            @Override
            public void onNext(List<BannerBean> bannerBeans) {
                LogUtil.e("获取Banner图片",bannerBeans.size()+"");
                bannerList.addAll(bannerBeans);
                vp_banner.getViewPager().getAdapter().notifyDataSetChanged();
            }
        };
        dataManager.getBanner(new ProgressObserver<ArrayList<BannerBean>>(listener,getActivity()),map);


    }


    private void getClassifyMenu()
    {

        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = DisplayUtil.dip2px(getActivity(),3);
        layoutParams.rightMargin = DisplayUtil.dip2px(getActivity(),3);

        dataManager = new DataManager();
        Map map = new HashMap();
        ObserverOnNextListener<List<MenuClassifyBean>> listener = new ObserverOnNextListener<List<MenuClassifyBean>>() {
            @Override
            public void onNext(List<MenuClassifyBean> menuClassifyBeans) {
                LogUtil.e("菜单列表",menuClassifyBeans.size()+"");
                menuClassifyList.addAll(menuClassifyBeans);
                menuItemAdapter.notifyDataSetChanged();
                rv_menu_list.post(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < scrollHelper.getPageCount(); i++) {
                            ImageView imageView = new ImageView(getActivity());
                            imageView.setImageResource(R.mipmap.index_off);
                            imageView.setLayoutParams(layoutParams);
                            ll_index_circle.addView(imageView);
                        }
                        if (ll_index_circle.getChildCount()>0)
                        {
                            ((ImageView)ll_index_circle.getChildAt(0)).setImageResource(R.mipmap.index_on);
                        }
                    }
                });
            }
        };
        dataManager.getclassifyfist(new ProgressObserver<ArrayList<MenuClassifyBean>>(listener,getActivity()),map);
    }


    @OnClick({ R.id.iv_shopping_message, R.id.ll_jinengzhuce,
            R.id.ll_fadanliebiao, R.id.ll_yijianfadan, R.id.ll_jiedanweizhi,
            R.id.ll_jiedanliebiao, R.id.ll_bendiyaowen, R.id.ll_gongxiangxinxi,
            R.id.rl_msg_num})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.iv_shopping_message:
                openList();//打开聊天列表
                break;
            case R.id.rl_msg_num:
                openList();//打开聊天列表
                break;
            case R.id.ll_jinengzhuce:
                Intent jinengIntent = new Intent(getActivity(), SkillRegisterActivity.class);
                startActivity(jinengIntent);
                break;
            case R.id.ll_fadanliebiao:
                Intent fadanlistIntent = new Intent(getActivity(), OrderSendActivity.class);
                startActivity(fadanlistIntent);
                break;
            case R.id.ll_yijianfadan:
                Intent fadanIntent = new Intent(getActivity(), OrderCreateActivity.class);
                startActivity(fadanIntent);
                break;
            case R.id.ll_jiedanweizhi:
                Intent weizhiIntent = new Intent(getActivity(), PositionActivity.class);
                startActivity(weizhiIntent);
                break;
            case R.id.ll_jiedanliebiao:
                Intent jiedanIntent = new Intent(getActivity(), OrderTakeActivity.class);
                startActivity(jiedanIntent);
                break;
            case R.id.ll_bendiyaowen:
                Intent newsIntent = new Intent(getActivity(), LocationNewsActivity.class);
                startActivity(newsIntent);
                break;
            case R.id.ll_gongxiangxinxi:
                Intent sharemsgIntent = new Intent(getActivity(), ShareMessageClassifyActivity.class);
                startActivity(sharemsgIntent);
                break;
        }
    }
    public void openList() {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put(Conversation.ConversationType.PRIVATE.getName(), false); //设置私聊会话是否聚合显示
        map.put(Conversation.ConversationType.GROUP.getName(), false);//群组
        map.put(Conversation.ConversationType.PUBLIC_SERVICE.getName(), false);//公共服务号
        map.put(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(),false);//订阅号
        map.put(Conversation.ConversationType.SYSTEM.getName(), false);//系统
        map.put(Conversation.ConversationType.DISCUSSION.getName(), false);
        RongIM.getInstance().startConversationList(getActivity(),map);
    }

    @Override
    public void onCountChanged(int count) {
        if (count == 0) {
            tvMsgNum.setVisibility(View.GONE);
        } else if (count > 0 && count < 100) {
            tvMsgNum.setVisibility(View.VISIBLE);
            tvMsgNum.setText(String.valueOf(count));
        } else {
            tvMsgNum.setVisibility(View.VISIBLE);
            tvMsgNum.setText(R.string.no_read_message);
        }
    }

    private void getReadState_DJD()
    {
        dataManager = new DataManager();
        Map<String ,String> map = new HashMap<>();
        map.put("type","2");
        ObserverOnNextListener<ReadStatusBean> listener = new ObserverOnNextListener<ReadStatusBean>() {
            @Override
            public void onNext(ReadStatusBean readStatusBean) {
                if (readStatusBean.getHaveRead()==1)
                {
                    iv_isRead.setVisibility(View.VISIBLE);
                }
                else if (readStatusBean.getHaveRead()==0)
                {
                    iv_isRead.setVisibility(View.GONE);
                }

            }
        };
        dataManager.orderlist_mainpage_read_status(new ProgressObserver<ReadStatusBean>(listener,getActivity()),map);
    }

    private void getReadState_Send_DJD()
    {
        dataManager = new DataManager();
        Map<String ,String> map = new HashMap<>();
        map.put("type","1");
        ObserverOnNextListener<ReadStatusBean> listener = new ObserverOnNextListener<ReadStatusBean>() {
            @Override
            public void onNext(ReadStatusBean readStatusBean) {
                if (readStatusBean.getHaveRead()==1)
                {
                    iv_isRead_send.setVisibility(View.VISIBLE);
                }
                else if (readStatusBean.getHaveRead()==0)
                {
                    iv_isRead_send.setVisibility(View.GONE);
                }

            }
        };
        dataManager.orderlist_mainpage_read_status(new ProgressObserver<ReadStatusBean>(listener,getActivity()),map);
    }

    @Override
    public void onResume() {
        super.onResume();
        getReadState_DJD();
        getReadState_Send_DJD();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RongIM.getInstance().removeUnReadMessageCountChangedObserver(this);
    }
}
